package com.hqyj.javaSpringBoot.modules.common.controller;

import com.hqyj.javaSpringBoot.modules.common.entity.ImageType;
import com.hqyj.javaSpringBoot.modules.common.entity.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class EnumDictionaryController {

    private final static Logger LOGGER = LoggerFactory.getLogger(EnumDictionaryController.class);

    // 将 N 个枚举对象放到 map
    public static Map<String, Object> enumMap = new HashMap() {{
        put("imageType", ImageType.class);
        put("resultCode", Result.ResultCode.class);
    }};

/*    static {
        menuMap.put("imageType", ImageType.class);
        menuMap.put("resultCode", Result.ResultCode.class);
    }*/

    /**
     * 127.0.0.1:8080/api/dictionary/imageType ---- get
     */
    @GetMapping("/dictionary/{enumKey}")
    public List<Object> getEnumDictionary(@PathVariable String enumKey){
        try {
            // 根据请求路径，获取 key ，对应拿到枚举的类模板
            Class clazz = (Class) enumMap.get(enumKey);
            if (clazz == null) {
                return null;
            }

            // 反射调用 values 方法，获得枚举数据
            Method method = clazz.getDeclaredMethod("values");
            Object[] objects = (Object[]) method.invoke(null);

            // 转化为 list 返给前端
            return Arrays.asList(objects);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.debug(e.getMessage());
        }
        return null;
    }
}
